#coding=utf-8
from django.shortcuts import render, redirect,render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.models import User
from django.db.models import Q
from models import *
from forms import *
import time,datetime
from django.utils import timezone

def my_username(request):
    username = request.session.get('username','')
    if username != '':
        user = username[0]
    else:
        user = ''
    return user
# 分页
def my_paginator(request, blogs, after_range_num, befor_after_num, pagination_num):
    after_r_num = after_range_num
    befor_r_num = befor_after_num
    paginator  = Paginator(blogs,pagination_num)
#     page:urls page value
    page = int(request.GET.get('page',1))
#     print page
    try:
#         get page data
        blogs_list = paginator.page(page)
    except PageNotAnInteger:
        blogs_list = paginator.page(1)
    except EmptyPage:
#         num_pages:the total number of pages,url default first if the argv page is empty
        blogs_list = paginator.page(paginator.num_pages)
#         通过设置after_range_num befor_range_num两个值以及下面的逻辑，进行处理多分页的时候，最多只显示5页
    if page >= after_range_num:
        page_range = paginator.page_range[page - after_r_num : page + befor_r_num]
    else:

        page_range = paginator.page_range[0 : after_r_num + befor_r_num]
#     page_num = paginator.page_range
#     print page_num
#     print page_range
#     返回的时候多返回一个range,这样在模板中就可以调用动态返回的显示页数返回
    return blogs_list, page_range

# 文章最新最热列表
def blog_list(request, type='blog'):
    username = request.session.get('username','')

    if  username != '':
        user = username[0]
#    使用双下划线__获取对应外键的值其中username为UserModel中对应用户名的字段名称
        if type == 'new':
            blogs = Blog.objects.filter(author__username__exact=user).filter(~Q(blogtype_id=2)).order_by('-id').all()[0:25]
        elif type == 'last':
            blogs = Blog.objects.filter(author__username__exact=user).filter(~Q(blogtype_id=2)).order_by('-clicktime').filter(clicktime__gt=10)
        elif type == 'blog':
            blogs = Blog.objects.filter(~Q(blogtype_id=2)).order_by('-id').filter(blogtype_id=1)
    else:
        user = ''
        if type == 'new':
            blogs = Blog.objects.filter(~Q(blogtype_id=2)).order_by('-id').all()[0:25]
        elif type == 'last':
            blogs = Blog.objects.filter(~Q(blogtype_id=2)).order_by('-clicktime').filter(clicktime__gt=10)
        elif type == 'blog':
            blogs = Blog.objects.filter(~Q(blogtype_id=2)).order_by('-id').filter(blogtype_id=1)

    blogs_list,page_range = my_paginator(request, blogs, 3, 2, 30)
    types = Type.objects.all()
    pics = PicInfo.objects.order_by('-id').all()[0:5]
    return render_to_response('blog_list.html', {
        'blogs':blogs_list,
        'pages_range':page_range,
        'username':user,
        'types':types,
        'pics':pics
    })

# 文章浏览
def blog_view(request,blogid):
    title_blog = '博文'
    href_blog = '/blog/list/type=all/'

    title_learn = '学无止境'
    href_learn = '/blog/learn/'

    user = my_username(request)
#    浏览次数
    blog = Blog.objects.get(id=blogid)
    blog.clicktime += 1
    blog.save()
#     获取评论次数
    comments = Comment.objects.filter(blog=blogid).order_by('-id')

    form = CommentForm()

#     上一篇  下一篇逻辑
    count = Blog.objects.all().count()
    num = int(blogid)
    nextid = num
    preid = num

    if num == 1:
        nextid = nextid+1
        next = Blog.objects.get(id=nextid)
        while next.blogtype_id ==2 or next.blogtype_id ==3:
            nextid = nextid+1
            next = Blog.objects.get(id=nextid)
        pre = Blog.objects.get(id=blogid)
    elif num == count:
        preid = preid - 1
        pre = Blog.objects.get(id=preid)
        while pre.blogtype_id ==2 or pre.blogtype_id ==3:
            preid = preid+1
            pre = Blog.objects.get(id=preid)
        next = Blog.objects.get(id=blogid)
    else:
        preid = preid - 1
        pre = Blog.objects.get(id=preid)
        while pre.blogtype_id ==2 or pre.blogtype_id ==3:
            preid = preid-1
            pre = Blog.objects.get(id=preid)

        nextid = nextid+1
        if nextid >= count:
            next = Blog.objects.get(id=blogid)
        else:
            next = Blog.objects.get(id=nextid)
            while next.blogtype_id ==2 or next.blogtype_id ==3:
                nextid = nextid+1
                if nextid >= count:
                    next = Blog.objects.get(id=blogid)
                else:
                    next = Blog.objects.get(id=nextid)
#        右侧推荐位
    learn_blogs = Blog.objects.order_by('-id').filter(blogtype_id__gt=5)[0:5]
    new_blogs = Blog.objects.order_by('-id').filter(blogtype_id=1)[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]
    types = Type.objects.filter(id__gt=6)

    if blog.blogtype_id == 1:
        return render_to_response("blog_view.html", {
                'blog':blog,
                'username':user,
                'form':form,
                'comments':comments,
                'title':title_blog,
                'href':href_blog,
                'pre':pre,
                'next':next,
                'newblogs': new_blogs,
                'travels': travels,
                'pics': pics,
                'types': types,
                'learnblogs':learn_blogs
                })
    elif blog.blogtype_id > 3:
        return render_to_response("blog_view.html", {
                'blog':blog,
                'username':user,
                'form':form,
                'comments':comments,
                'title':title_learn,
                'href':href_learn,
                'pre':pre,
                'next':next,
                'newblogs': new_blogs,
                'travels': travels,
                'pics': pics,
                'types': types,
                'learnblogs':learn_blogs
                })

# 文章点评
def blog_comment(request,blogid):
    user = my_username(request)
    blog = Blog.objects.get(id=blogid)
    comments = Comment.objects.filter(blog=blogid).order_by('-id')
    if request.method == 'POST':
        commentform = CommentForm(data=request.POST)
#         print commentform.is_valid()
        if commentform.is_valid():
            Comment.objects.create(content=request.POST['content'], blog=blog,timestamp=timezone.now(),agree=0)
            return redirect('/blog/article/'+str(blogid)+'/')
    return render(request, 'blog_view.html', {
        'username':user,
        'blog':blog,
        'form':commentform,
        'comments': comments
    })

# 摄影作品展示，
def blog_pic(request):
    user = my_username(request)

    pics = PicInfo.objects.order_by('-id').all()
    pics_list,page_range = my_paginator(request, pics, 3, 2, 60)

#     右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:3]

    return render_to_response('blog_pic.html', {
            'pics':pics_list,
            'pages_range':page_range,
            'username':user,
            'newblogs':new_blogs,
            'travels':travels
            })

#影集浏览
def blog_pic_view(request, picid):
    user = my_username(request)
    picinfo = PicInfo.objects.get(id=picid)
    picinfo.clicktime += 1
    picinfo.save()
    pics = Pic.objects.filter(picinfo_id=picid)
    comments = PicComment.objects.order_by('-id').filter(picInfo_id=picid)
    form = PicCommentForm()

#     右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:5]

    return render_to_response("blog_pic_view.html",{
        'username':user,
        'pics': pics,
        'picinfo':picinfo,
        'comments':comments,
        'newblogs': new_blogs,
        'form':form,
        'travels': travels
        })

#摄影集评论
def blog_pic_comment(request, picid):
    user = my_username(request)
    contents = PicComment.objects.order_by('-id').filter(picInfo_id=picid)
    picinfo = PicInfo.objects.get(id=picid)
    pics = Pic.objects.filter(picinfo_id=picid)
    comments = PicComment.objects.order_by('-id').filter(picInfo_id=picid)

    form = PicCommentForm()
    if request.method == 'POST':
        form = PicCommentForm(data = request.POST)
#         print  form.is_valid()
        if form.is_valid():
            PicComment.objects.create(picInfo=picinfo, content=request.POST['content'],timestamp=timezone.now())
            return redirect('/blog/pic/'+str(picid)+'/')

    return render(request, "blog_pic_view.html",{'username':user, 'pics':pics, 'form':form,'comments':comments,'picinfo':picinfo})

# 段子,未完成
def blog_happy(request):
    user = my_username(request)

    blogs = Blog.objects.filter(blogtype_id=2).order_by('-id')
    blogs_list,page_range = my_paginator(request, blogs, 3, 2, 50)

#    右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:3]

    return render_to_response('blog_happy.html', {
            'blogs':blogs_list,
            'pages_range':page_range,
            'username':user,
            'newblogs': new_blogs,
            'pics':pics,
            'travels': travels
            })

#增加段子
def blog_happy_add(request):
#     username = request.session.get('username','')
#     user = username[0]
    author_ = User.objects.get(id = 1)
    err_msg = ''
    if request.method == 'POST':
        blog_type = Type.objects.get(id=2)

        blog = Blog.objects.create(
            author = author_,
            blogtype = blog_type,
            title = timezone.now(),
            body = request.POST['body'],
            timestamp = timezone.now(),
            clicktime = 0,
        )
        blog.save()
        return redirect('/blog/happy/')

#旅行列表
def blog_travel(request):
    user = my_username(request)

    travels = TravelInfo.objects.order_by('-id').all()
    travels_list,page_range = my_paginator(request, travels, 3, 2, 20)

#    右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]

    return render_to_response('blog_travel.html', {
            'travels':travels_list,
            'pages_range':page_range,
            'username':user,
            'pics':pics,
            'newblogs':new_blogs
            })

#旅行日志浏览
def blog_travel_view(request, travelid):
    user = my_username(request)

#     获取旅行日志基本信息
    travelinfo = TravelInfo.objects.get(id=travelid)
    travelinfo.clicktime += 1
    travelinfo.save()
#     获取旅行日志的具体人欧冠
    travels = Travel.objects.filter(body_id=travelid)
#    右侧推荐
    picall = PicInfo.objects.order_by('-id').all()[0:5]
    new_blogs = Blog.objects.order_by('-id').filter(blogtype_id=1)[0:5]
    return render_to_response("blog_travel_view.html",{
        'username':user,
        'travelinfo': travelinfo,
        'travels': travels,
        'picall':picall,
        'newblogs': new_blogs
        })


# 学无止境
def blog_learn(request):
    user = my_username(request)
    typeid = 0
    blogs = Blog.objects.order_by('-id').filter(blogtype_id__gt=5)
    blogs_list,page_range = my_paginator(request, blogs, 3, 2, 25)
    types = Type.objects.filter(id__gt=6)

#    右侧推荐
    travels = TravelInfo.objects.order_by('-id').all()[0:5]
    new_blogs = Blog.objects.order_by('-id').filter(blogtype_id=1)[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]

    return render_to_response('blog_learn.html', {
        'blogs':blogs_list,
        'pages_range':page_range,
        'username':user,
        'types':types,
        'newblogs': new_blogs,
        'pics':pics,
        'typeid':typeid,
        'travels': travels
    })


# 学习技能点分类
def blog_learn_type(request, typeid):
    user = my_username(request)

    blogs = Blog.objects.filter(blogtype_id=typeid)
    blogs_list,page_range = my_paginator(request, blogs, 3, 2, 20)
    type = Type.objects.get(id=typeid)
    types = Type.objects.filter(id__gt=6)

#  右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(blogtype_id=1)[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]

    return render_to_response('blog_learn.html', {
        'blogs':blogs_list,
        'pages_range':page_range,
        'username':user,
        'types':types,
        'typeid':typeid,
        'type': type,
        'newblogs': new_blogs,
        'travels': travels,
        'pics': pics
    })




# 个人中心设置
def blog_profile(request):
    user = my_username(request)

    contents = LeaveAMsg.objects.order_by('-id').all()
    form = LeaveAMsgForm()

#    右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:3]

    try:
        profile = Profile.objects.get(name=1)
    except Exception as e:
        return render_to_response("blog_profile.html",{
            'username':user,
            'contents':contents,
            'form':form,
            'newblogs':new_blogs,
            'pics':pics,
            'travels':travels
        })
    return render_to_response("blog_profile.html",{
        'username':user,
        'profile': profile,
        'contents':contents,
        'form':form,
        'newblogs':new_blogs,
        'pics':pics,
        'travels':travels
    })

def blog_leave_msg(request):
    user = my_username(request)
    err_msg = ''
    contents = LeaveAMsg.objects.order_by('-id').all()
    form = LeaveAMsgForm()
    if request.method == 'POST':
        form = LeaveAMsgForm(data = request.POST)
#         print  form.is_valid()
        if form.is_valid():
            LeaveAMsg.objects.create(content=request.POST['content'],timestamp=timezone.now())
            return redirect('/blog/profile/')
        err_msg = '发表失败'
    try:
        profile = Profile.objects.get(name=1)
    except Exception as e:
        return render_to_response("blog_profile.html",{'username':user, 'contents':contents, 'form':form})
    return render_to_response("blog_profile.html",{'username':user,'profile': profile, 'contents':contents, 'form':form})

#     return render("blog_profile.html",{'username':user,'profile': profile, 'form':form})?

# 闲言碎语，未完成
def blog_xysy(request):
    user = my_username(request)
    xysys = Xysy.objects.order_by('-id').all()

#    右侧推荐
    new_blogs = Blog.objects.order_by('-id').filter(~Q(blogtype_id=2))[0:5]
    pics = PicInfo.objects.order_by('-id').all()[0:5]
    travels = TravelInfo.objects.order_by('-id').all()[0:3]

    return render_to_response("blog_xysy.html",{
        'username':user,
        'xysys':xysys,
        'newblogs':new_blogs,
        'pics':pics,
        'travels':travels
    })


# 登录
def home(request):
    return render_to_response('blog_login.html',{'username':''})

# bolg登录
def blog_login(request):
    username = request.POST.get('username','')
    password = request.POST.get('password','')
    users_ = [username]
    user = auth.authenticate(username=username, password=password)
    if user is not None:
        auth.login(request, user)
        response = redirect('/blog/list/type=new/')
        request.session['username'] = users_
        return response
    else:
        return render_to_response('blog_login.html', {'error':'用户名或密码错误，请重新输入！','username':''})

# blog退出
@login_required
def blog_logout(request):
    response = redirect('/blog/list/type=new/')
#     auth.logout(request)
# clear cookie
#     response.delete_cookie('username')
# clear session
    del request.session['username']
    return response

# 添加blog
@login_required
def blog_add(request):
    username = request.session.get('username','')
    user = username[0]
    author_ = User.objects.get(username = user)
    err_msg = ''

#     timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    blogform = BlogForm()
    if request.method == 'POST':
        blogform = BlogForm(data=request.POST)
        blog_type = Type.objects.get(id=1)

        if blogform.is_valid():
            Blog.objects.create(
                author = author_,
                blogtype = blog_type,
                title = request.POST['title'],
                body = request.POST['body'],
                timestamp = timezone.now(),
                clicktime = 0
            )
            blog = Blog.objects.get(title=request.POST['title'])
            url = '/blog/article/'+ str(blog.id) + '/'
            return redirect(url)
        err_msg = '发布失败'
    return render(request, "blog_add.html", {'username':user,'form':blogform, 'error': err_msg})
